# Arguments in the following format:
# database=192.68.0.1 appserver=192.168.0.2~192.168.0.3 jms=192.168.0.4 agent=import,search:192.168.0.5~export:192.168.0.6

#variables
WAS_DIR=/opt/IBM/WebSphere/AppServer
WAS_TEMP=/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/temp
serverName=server1
JAVA_PATH=/opt/IBM/WebSphere/AppServer/java
JMS_HOSTNAME=<%=@jmshost%>
DB_HOSTNAME=<%=@dbhost%>
current_ip=`/sbin/ifconfig  | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'`
current_ip=`echo $current_ip | cut -d\  -f1`

# Process command line arguments
args=($@)
for i in "${!args[@]}"; do 
  key=`echo ${args[$i]} | cut -d= -f1`
  val=`echo ${args[$i]} | cut -d= -f2`

  case "$key" in
  database) 
  IFS='~' read -a db_ip_arr <<< "${val}"
  ;;
  appserver)
  IFS='~' read -a appserver_ip_arr <<< "${val}"
  ;;
  jms)
  IFS='~' read -a jms_ip_arr <<< "${val}"
  ;;
  agent)
  IFS='~' read -a agent_ip_arr <<< "${val}"
  ;;	
  esac 	
done

# Map the database host name
sudo sh -c "echo ${db_ip_arr[0]} $DB_HOSTNAME >>/etc/hosts"

# Map the jms host name
sudo sh -c "echo ${jms_ip_arr[0]} $JMS_HOSTNAME >>/etc/hosts"

# Map the current host name
NEW_HOSTNAME=`hostname`
sudo sh -c "echo ${current_ip} $NEW_HOSTNAME >>/etc/hosts"

# Remove temp files
sudo rm -rf $WAS_TEMP	


# Update server index
OLDURL=`sed -n 's/.*hostName="\([^"]*\)".*/\1/ p' /opt/IBM/WebSphere/AppServer/profiles/AppSrv01/config/cells/*/nodes/*/serverindex.xml`
#`sed -n 's/.*hostName="\([^"]*\)".*/\1/ p' serverindex.xml`
HOSTNAME=`hostname`
cd /opt/IBM/WebSphere/AppServer/profiles/AppSrv01/config/cells/*/nodes/*/
sudo cp serverindex.xml /tmp
sed "s/$OLDURL/$HOSTNAME/" </tmp/serverindex.xml > /tmp/serverindex.xml.mod
sudo mv /tmp/serverindex.xml.mod serverindex.xml
sudo chown wasuser:wasgroup serverindex.xml
sudo rm /tmp/serverindex.xml

# Add the WAS service in system startup
sudo chkconfig wasservice --add

# Start WAS Server
sudo service wasservice start